package com.example.translateappjava.Repository;

import android.app.Application;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.example.translateappjava.DataBase.PostDao;
import com.example.translateappjava.DataBase.AppDatabase;
import com.example.translateappjava.Utils.Post;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class PostRepository {
    private static final String TAG = "PostRepository";
    private PostDao postDao;
    private ExecutorService executorService;
    private Handler mainThreadHandler = new Handler(Looper.getMainLooper());

    public interface RepositoryCallback<T> {
        void onSuccess(T result);
        void onError(Exception e);
    }
    public interface OperationStatusCallback {
        void onSuccess();
        void onError(Exception e);
    }


    public PostRepository(Application application) {
        AppDatabase db = AppDatabase.getDatabase(application);
        postDao = db.postDao();
        executorService = Executors.newSingleThreadExecutor();
    }

    public void insertAllPosts(List<Post> posts, OperationStatusCallback callback) {
        executorService.execute(() -> {
            try {
                Log.d(TAG, "Deleting all posts from DB.");
                postDao.deleteAllPosts(); // 首先删除所有旧帖子
                Log.d(TAG, "Inserting " + posts.size() + " new posts into DB.");
                postDao.insertAllPosts(posts); // 插入从服务器获取的新帖子列表
                mainThreadHandler.post(callback::onSuccess);
            } catch (Exception e) {
                Log.e(TAG, "Error in insertAllPosts (syncing from server): ", e);
                mainThreadHandler.post(() -> callback.onError(e));
            }
        });
    }

    public void insertPost(Post post, OperationStatusCallback callback) {
        executorService.execute(() -> {
            try {
                // 当插入单个新帖子时，它的 serverId 可能已经是服务器返回的，或者为null（如果逻辑是先本地存再上传）
                // Room 会为它生成 localId
                Log.d(TAG, "Inserting post with ServerID: " + post.getServerId() + " into DB.");
                postDao.insertPost(post);
                mainThreadHandler.post(callback::onSuccess);
            } catch (Exception e) {
                Log.e(TAG, "Error in insertPost (saving new post locally): ", e);
                mainThreadHandler.post(() -> callback.onError(e));
            }
        });
    }

    public void getAllPosts(RepositoryCallback<List<Post>> callback) {
        executorService.execute(() -> {
            try {
                Log.d(TAG, "Fetching all posts from DB.");
                List<Post> posts = postDao.getAllPosts(); // 这个方法返回按时间排序的帖子
                mainThreadHandler.post(() -> callback.onSuccess(posts));
            } catch (Exception e) {
                Log.e(TAG, "Error in getAllPosts: ", e);
                mainThreadHandler.post(() -> callback.onError(e));
            }
        });
    }

    // 如果你需要根据服务器ID获取单个帖子的方法
    public void getPostByServerId(Long serverId, RepositoryCallback<Post> callback) {
        if (serverId == null) {
            Log.w(TAG, "getPostByServerId called with null serverId.");
            mainThreadHandler.post(() -> callback.onError(new IllegalArgumentException("Server ID cannot be null")));
            return;
        }
        executorService.execute(() -> {
            try {
                Log.d(TAG, "Fetching post by ServerID: " + serverId + " from DB.");
                Post post = postDao.getPostByServerId(serverId); // 使用新的DAO方法
                mainThreadHandler.post(() -> callback.onSuccess(post)); // post 可能为 null 如果没找到
            } catch (Exception e) {
                Log.e(TAG, "Error in getPostByServerId: ", e);
                mainThreadHandler.post(() -> callback.onError(e));
            }
        });
    }

    // 你可能还需要一个 updatePost 方法，如果服务器返回的Post对象需要更新本地已存在的记录
    // 例如，当从服务器拉取帖子详情时，如果本地已有，则更新
    public void updatePost(Post post, OperationStatusCallback callback) {
        executorService.execute(() -> {
            try {
                Log.d(TAG, "Updating post with ServerID: " + post.getServerId() + " in DB.");
                postDao.updatePost(post); // Room update 通常基于 @PrimaryKey (localId)
                // 你需要确保更新时 post 对象有正确的 localId
                // 或者你的 updatePost DAO方法是基于 serverId 更新的
                mainThreadHandler.post(callback::onSuccess);
            } catch (Exception e) {
                Log.e(TAG, "Error in updatePost: ", e);
                mainThreadHandler.post(() -> callback.onError(e));
            }
        });
    }
}